<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 内容区放表单 -->
    <el-form label-width="80px" :model="userInfo" :rules="rules" ref="from">
      <el-form-item label="登录账号">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">确认修改</el-button>
        <el-button @click="resetFrom">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user'
export default {
  data() {
    return {
      // userInfo: {
      //   username: this.$store.state.user.user.username,
      //   nickname: this.$store.state.user.user.nickname,
      //   email: this.$store.state.user.user.email
      // }
      // 使用浅拷贝
      userInfo: { ...this.$store.state.user.user },
      rules: {
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '昵称长度在 1~10 位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      this.$refs.from.validate(async valid => {
        if (!valid) return
        const { data: res } = await updateUserAPI(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 更新vuex中的数据,调用actions中的方法，重新获取数据
          // this.$store.dispatch('user/getUser')
          // 把传的数据浅拷贝一下，让原始数据和修改后的数据分开，两个单独的对象
          this.$store.commit('user/updateUser', { ...this.userInfo })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 重置表单
    resetFrom() {
      // resetFields 恢复到最初的样子，取消错误提示
      this.$refs.from.resetFields()
      // 将vuex中的数据，更新到组件中
      this.userInfo = { ...this.$store.state.user.user }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
